package cn.inst.common.security;

import javax.annotation.Resource;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import cn.inst.user.domain.Permission;
import cn.inst.user.domain.Role;
import cn.inst.user.domain.User;
import cn.inst.user.service.UserService;

public class MyRealm extends AuthorizingRealm{
	@Autowired
	private UserService userServiceImp;
	
	/**
	 * 授权的方法
	 * 把权限ADD到subject
	 */
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		System.out.println("进入授权方法");
		User user = (User) principals.getPrimaryPrincipal();
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		//授权
		for (Role role : user.getRoleList()) {
			for (Permission permission : role.getPermissionList()) {
				authorizationInfo.addStringPermission(permission.getPermission());
			}
		}
		return authorizationInfo;
	}
	/**
	 * 登录认证的方法
	 * 即获取user
	 */
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		//token:页面传过来的user
		UsernamePasswordToken usernamePasswordToken=(UsernamePasswordToken) token;
		String username=usernamePasswordToken.getUsername();
		//通过username查找user
		User user=userServiceImp.findUserByUsername(username);
		if(user==null){
			return null;
		}else{
			//把user对象与线程绑定,user密码放到info,然后调用认证管理器
			AuthenticationInfo info=new  SimpleAuthenticationInfo(user,user.getPassword(), getName());
			return info;
		}
	}

}
